package com.syqc.monitor.ui.cost

import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.syqc.comlib.databinding.DialogMessageBinding
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.comlib.utils.loadStringDImgError
import com.syqc.entity.KeyValue
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentOilBinding
import com.syqc.monitor.databinding.IncludeSelectSureBinding
import com.syqc.monitor.ui.newaddcar.KeyValuePopup
import com.syqc.utils.InputUtil
import com.syqc.utils.Keys

class OilFragment : BaseFeeFragment<FragmentOilBinding>(FragmentOilBinding::inflate) {

    private lateinit var sureBinding: IncludeSelectSureBinding
    private val mOilTypePopup by lazy { KeyValuePopup(requireContext()) }
    private val mOilCardPopup by lazy { KeyValuePopup(requireContext()) }

    private val mAdapter by lazy { PhotoAdapter() }

    private val mVM by viewModels<OilViewModel>()

    override val mViewModel: BaseFeeViewModel
        get() = mVM

    override val isOil: Boolean
        get() = true

    override fun setDate(type: Int, time: String) {
        binding.lrvDate.setRightText(time)
        mVM.update = time
    }

    override fun uploadData() {
        mVM.uploadOil()
    }

    override fun clearData() {
        binding.uetAdd.setText("")
        binding.uetPrice.setText("")
        binding.uetMile.setText("")
        binding.lrvOilType.setRightText("")
        binding.editFeeRemark.setText("")
        binding.uetTotal.setText("0.00")
        binding.lrvOilCard.setRightText("")
        binding.lrvOilType.setRightText("")
        binding.lrvOilPeople.setRightText("")

        mVM.clearData()
    }

    override fun initView(view: View) {

        sureBinding = IncludeSelectSureBinding.bind(binding.root)
        sureBinding.tvSure.setText(R.string.desc_com_sure)
        focusChange(binding.uetAdd.getEditText())
        focusChange(binding.uetPrice.getEditText())
        focusChange(binding.uetMile.getEditText())
        InputUtil.editTextNested(binding.editFeeRemark)
        binding.lrvDate.setRightText(mVM.update)

        binding.uetTotal.getEditText().isEnabled = false

        binding.recyclerOil.layoutManager = GridLayoutManager(requireContext(), 3)
        binding.recyclerOil.adapter = mAdapter
    }

    override fun initEvent() {
        binding.lrvDate.setOnClickListener {
            mDatePicker.show(mVM.update)
        }

        binding.uetAdd.setOnTextChange {
            val str = isNumOk(binding.uetAdd, it)
            mVM.feeAdd = str
        }

        binding.uetPrice.setOnTextChange {
            val str = isNumOk(binding.uetPrice, it)
            mVM.feePrice = str
        }

        binding.uetMile.setOnTextChange {
            val str = isNumOk(binding.uetMile, it)
            mVM.mile = str
        }

        sureBinding.tvSure.filterFast {
            mVM.isStill = false
            mVM.uploadOil()
        }
        binding.editFeeRemark.doAfterChanged {
            mVM.remark = it
        }

        binding.lrvOilType.setOnClickListener {
            mOilTypePopup.showAtLocation(
                requireActivity().window.decorView,
                R.string.desc_add_oil_type,
                mVM.getOilTypes(),
                mVM.oilIndex
            )
        }

        mOilTypePopup.setCallBack(object : KeyValuePopup.CallBack {
            override fun onBack(entity: KeyValue, index: Int) {
                mVM.oiltype = entity.key
                mVM.oilIndex = index
                binding.lrvOilType.setRightText(entity.value)
            }
        })

        binding.lrvOilCard.setOnClickListener {
            if (mVM.getKVs().isEmpty()) showToast(R.string.toast_no_oil_card)
            else mOilCardPopup.showAtLocation(
                requireActivity().window.decorView,
                R.string.desc_oil_card,
                mVM.getKVs(),
                mVM.chooseIndex
            )
        }
        mOilCardPopup.setCallBack(object : KeyValuePopup.CallBack {
            override fun onBack(entity: KeyValue, index: Int) {
                mVM.oilCardNo = entity.key
                mVM.chooseIndex = index
                mVM.setChooseOilCard(index)
                binding.lrvOilCard.setRightText(entity.value)
            }
        })
        binding.lrvOilPeople.setOnClickListener {
            launcherPeople.launchAct<DriversActivity>(requireContext()) {
                putExtra("isDriver", false)
            }
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            mVM.photoIndex = position
            val path = mAdapter.data[position]
            if (path.isEmpty()) {
                takePhoto()
            }
        }
        mAdapter.setOnItemChildClickListener { _, _, position ->
            mAdapter.data[position] = ""
            mAdapter.notifyItemChanged(position)
            mVM.removeIndexPhoto(position)
        }
    }

    override fun initData() {
        super.initData()

        mVM.getOilCard()

        mVM.feeTotalLive.observe(this) {
            binding.uetTotal.setText(it)
        }
        mVM.cardLive.observe(this) {
            if (it) showCardDialog()
        }
        mVM.photoOilLive.observe(this) {
            mAdapter.setList(it)
        }
    }

    private var privacyDialog: AlertDialog? = null

    private fun showCardDialog() {
        if (privacyDialog == null) {
            val builder = AlertDialog.Builder(requireContext(), R.style.GspTheme_Dialog)
            val view = DialogMessageBinding.inflate(layoutInflater)
            builder.setView(view.root)

            view.tvMessage.setText(R.string.desc_oil_card_null)

            view.tvNegative.setOnClickListener {
                privacyDialog?.dismiss()
            }

            view.tvPositive.setOnClickListener {
                privacyDialog?.dismiss()
                mVM.isStill = true
                mVM.uploadOil()
            }

            privacyDialog = builder.create()
        }
        if (!requireActivity().isFinishing) privacyDialog?.show()
    }

    private val launcherPeople = registerResultOk { result ->
        mVM.peopleId = result.data?.getStringExtra(Keys.INTENT_ID) ?: ""
        mVM.peopleName = result.data?.getStringExtra(Keys.INTENT_OTHER) ?: ""
        binding.lrvOilPeople.setRightText(mVM.peopleName)
    }

    override fun onDestroy() {
        super.onDestroy()
        privacyDialog?.dismiss()
        privacyDialog = null
    }

}

class PhotoAdapter() : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_oil_photo) {
    init {
        addChildClickViewIds(R.id.ivOilDelete)
    }

    override fun convert(holder: BaseViewHolder, item: String) {
        val typeId = when (holder.layoutPosition) {
            0 -> {
                R.string.desc_oil_type_one
            }

            1 -> {
                R.string.desc_oil_type_two
            }

            else -> {
                R.string.desc_oil_type_three
            }
        }
        holder.setText(R.id.tvOilType, typeId)
        holder.getView<ImageView>(R.id.ivOilPhoto)
            .loadStringDImgError(context, item, R.mipmap.ic_repair_default)
        val ivOilDelete = holder.getView<View>(R.id.ivOilDelete)
        ivOilDelete.visibility = if (item.isEmpty()) View.GONE else View.VISIBLE
    }

}